//
//  PayManager.m
//  BDD
//
//  Created by Eton on 2017/4/8.
//  Copyright © 2017年 APE. All rights reserved.
//

#import "PayManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "PayParameterInfo.h"

//支付宝 错误码
#define SUCCESSFUL_STATUS @"9000"
#define ORDER_PAY_FALSE @"4000"
#define NET_ERROR @"6002"
#define USER_CANCEL @"6001"


@implementation PayManager

+ (instancetype) shareInstance
{
    static PayManager* __payManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __payManager = [[PayManager alloc] init];
    });
    return __payManager;
}

#pragma mark - 调起支付
-(void) payWithPayPlatform:(PayPlatformType)type parameterInfo:(PayParameterInfo*)params callBackBlock:(PayCompletionBlock)completionBlock{
    if (type == PayPlatformType_Alipay) {
        [self payByAlixPayWithSign:params.sign callBackBlock:completionBlock];
    }else if (type == PayPlatformType_Wechat){
        [self payByWeiXinWithPartnerId:params.partnerid prepayId:params.prepayid nonceStr:params.noncestr timeStamp:[params.timestamp doubleValue] package:params.package sign:params.sign callBackBlock:completionBlock];
    }
}

#pragma mark - 支付宝支付
/**
 *  调起 - 支付宝支付
 */
- (void) payByAlixPayWithSign:(NSString *)sign callBackBlock:(PayCompletionBlock)completionBlock
{
    _completionBlock = completionBlock;
    
    kWeakSelf;
    NSDictionary *bundleUrltypes = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleURLTypes"];
    NSString * appscheme = [[bundleUrltypes allValues] firstObject];
    [[AlipaySDK defaultService] payOrder:sign fromScheme:appscheme callback:^(NSDictionary *resultDic) {
        //跳转钱包的回调，不会走这~~~
        weakSelf.resultDic = resultDic;
    }];
    
    
}

/**
 *   支付宝支付 - 结果
 */
- (void)setResultDic:(NSDictionary *)resultDic{
    NSString *status = [resultDic objectForKey:@"resultStatus"];
    NSString *meno = [resultDic objectForKey:@"memo"];
    if ([status isEqualToString:SUCCESSFUL_STATUS]) {
        //成功
        if (_completionBlock) {
            _completionBlock(PayResultType_Success, nil);
        }
        
    } else if ([status isEqualToString:ORDER_PAY_FALSE]) {
        //失败
        if (_completionBlock) {
            _completionBlock(PayResultType_Failed, meno);
        }
    } else if ([status isEqualToString:USER_CANCEL]) {
        //取消
        if (_completionBlock) {
            _completionBlock(PayResultType_Cancel, meno);
        }
    } else if ([status isEqualToString:NET_ERROR]) {
        //网络错误
        if (_completionBlock) {
            _completionBlock(PayResultType_NetError, meno);
        }
    }else{
        if (_completionBlock) {
            _completionBlock(PayResultType_Failed, meno);
        }
    }
}

#pragma mark - 微信支付
/**
 *  调起微信支付
 */
-(void) payByWeiXinWithPartnerId:(NSString*)partnerId
                        prepayId:(NSString*)prepayId
                        nonceStr:(NSString*)nonceStr
                       timeStamp:(NSTimeInterval)timeStamp
                         package:(NSString*)package
                            sign:(NSString*)sign
                   callBackBlock:(PayCompletionBlock)completionBlock
{
    _completionBlock = completionBlock;
    
    PayReq* req             = [[PayReq alloc] init];
    req.partnerId           = partnerId;
    req.prepayId            = prepayId;
    req.nonceStr            = nonceStr;
    req.timeStamp           = (UInt32)timeStamp;
    req.package             = package;
    req.sign                = sign;
    
    //    req.partnerId           = @"10000100";
    //    req.prepayId            = @"wx201601061632260a08785e440987115400";
    //    req.nonceStr            = @"590b09afb16979332598afa20ca75c22";
    //    req.timeStamp           = (UInt32)1452069146;
    //    req.package             = @"Sign=WXPay";
    //    req.sign                = @"CA9BADFAEEAA431DC7485AC7BB4EC743";
    
    
    [WXApi sendReq:req];
}
/**
 *   WXApiDelegate 微信支付 - 结果
 */
- (void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg = resp.errStr;
        
        switch (resp.errCode) {
            case WXSuccess:{
                //成功
                if (_completionBlock) {
                    _completionBlock(PayResultType_Success, nil);
                }
            }
                break;
            case WXErrCodeUserCancel:{
                //取消
                if (_completionBlock) {
                    _completionBlock(PayResultType_Cancel, @"用户中途取消");
                }
            }
                break;
                
            case WXErrCodeSentFail:{
                //发送失败
                if (_completionBlock) {
                    _completionBlock(PayResultType_Failed, strMsg?:@"支付失败");
                }
            }
                break;
            default:{
                if (_completionBlock) {
                    _completionBlock(PayResultType_Failed, strMsg?:@"支付失败");
                }
            }
                break;
        }
    }
    
}

@end
